package com.yundasys.lab02springbootstudy.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @PACKAGE_NAME: com.yundasys.lab02springbootstudy.future
 * @NAME: CompletableFuture2
 * @USER: jiangta
 * @DATE: 2021/12/8
 * @TIME: 12:34 下午
 * @PROJECT_NAME: springboot-labs
 */
public class CompletableFuture2 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> completableFuture=new CompletableFuture<String>();
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName()+"执行.....");
                    completableFuture.complete("success");//在子线程中完成主线程completableFuture的完成

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t1=new Thread(runnable);
        t1.start();//启动子线程

        String result= null;//主线程阻塞，等待完成
        try {
            result = completableFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"1x:  "+result);

        CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
                .thenApplyAsync(s -> s + "world!").thenApplyAsync(s -> s + "nice!");
        System.out.println(future.get());

    }
}
